package com.xsoft.demo9;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.Nullable;

public class CalendarItemView extends LinearLayout {
    private TextView date;
    private GridView gridView;
    private TextView selectDate;
    private TextView event;
    private GridViewAdapter adapter;
    private Calendar calendar;
    private int position;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
    private SimpleDateFormat itemFormat = new SimpleDateFormat("yyyy-MM-dd");
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), Utils.ACTION_UPDATE_CALENDAR)) {
                update(position);
            }
        }
    };

    public CalendarItemView(Context context) {
        super(context);
        View view = LayoutInflater.from(context).inflate(R.layout.item_calendar_view, this, false);
        addView(view);
        date = (TextView) findViewById(R.id.date);
        gridView = (GridView) findViewById(R.id.grid_view);
        selectDate = (TextView) findViewById(R.id.select_date);
        event = (TextView) findViewById(R.id.event);
        adapter = new GridViewAdapter();
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Utils.selectDate = ((CalendarBean) adapter.getItem(position)).date;
                getContext().sendBroadcast(new Intent(Utils.ACTION_UPDATE_CALENDAR));
            }
        });
    }

    public CalendarItemView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Utils.ACTION_UPDATE_CALENDAR);
        getContext().registerReceiver(receiver, filter);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getContext().unregisterReceiver(receiver);
    }

    public void update(int position) {
        this.position = position;
        calendar = calendar.getInstance();
        calendar.add(Calendar.MONTH, position - 1000);
        date.setText(format.format(calendar.getTime()));
        selectDate.setText(Utils.selectDate);
        event.setText(Utils.getSchedule(getContext(), Utils.selectDate));
        adapter.setDatas(initDatas());
    }

    private List<CalendarBean> initDatas() {
        List<CalendarBean> datas = new ArrayList<>();
        datas.add(new CalendarBean(null, "日", null, null));
        datas.add(new CalendarBean(null, "一", null, null));
        datas.add(new CalendarBean(null, "二", null, null));
        datas.add(new CalendarBean(null, "三", null, null));
        datas.add(new CalendarBean(null, "四", null, null));
        datas.add(new CalendarBean(null, "五", null, null));
        datas.add(new CalendarBean(null, "六", null, null));
        int days = Utils.getMonthOfDay(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
        for (int i = 1; i <= days; i++) {
            calendar.set(Calendar.DAY_OF_MONTH, i);
            if (i == 1) {
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                for (int j = 1; j < dayOfWeek; j++) {
                    datas.add(new CalendarBean(null, null, null, null));
                }
            }
            datas.add(new CalendarBean(itemFormat.format(calendar.getTime()), String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),
                    Utils.showHoliday ? Utils.getSolarHoliday(calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)) : null,
                    Utils.getSchedule(getContext(), itemFormat.format(calendar.getTime()))));
            if (i == days) {
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                for (int j = 0; j < 7 - dayOfWeek; j++) {
                    datas.add(new CalendarBean(null, null, null, null));
                }
            }
        }
        return datas;
    }

    public class GridViewAdapter extends BaseAdapter {
        private List<CalendarBean> datas;

        public void setDatas(List<CalendarBean> datas) {
            if (this.datas != null) {
                this.datas.clear();
            }
            this.datas = datas;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            Log.i("demo", "getCount");
            return datas == null ? 0 : datas.size();
        }

        @Override
        public Object getItem(int position) {
            Log.i("demo", "getItem position = " + position);
            return datas == null ? null : datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            Log.i("demo", "getItemId position = " + position);
            return datas == null ? 0 : position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_text, null);
            }
            ((TextView) convertView.findViewById(R.id.day)).setText(datas.get(position).day);
            ((TextView) convertView.findViewById(R.id.holiday)).setText(Utils.showHoliday ? datas.get(position).holiday : null);
            convertView.findViewById(R.id.holiday).setVisibility(TextUtils.isEmpty(datas.get(position).date) ? GONE : VISIBLE);

            convertView.findViewById(R.id.schedule).setVisibility(TextUtils.isEmpty(datas.get(position).date) ? GONE
                    : TextUtils.isEmpty(datas.get(position).schedule) ? INVISIBLE : VISIBLE);
            convertView.findViewById(R.id.item_text).setBackgroundColor(TextUtils.equals(datas.get(position).date, Utils.selectDate) ?
                    parent.getContext().getResources().getColor(R.color.colorPrimary) : 0);
            return convertView;
        }
    }
}
